<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable="false" show-icon></el-alert>
      <div style="margin-top:15px">
        选择商品分类：
        <el-cascader
          v-model="cascAllData"
          :options="paramsList"
          :props="getPropsParams"
          @change="cascderHandleChange"
        ></el-cascader>
        <el-tabs v-model="activeName" @tab-click="tabHandleClick">
          <el-tab-pane label="动态参数" name="many">
            <el-button type="primary" size="mini" :disabled="isdisab" @click="showManyDate">添加参数</el-button>
            <el-table :data="manyTableList" style="width: 100%" border stripe>
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag @close="removeTag(i,scope.row)" closable v-for=" (item,i) in scope.row.attr_vals" :key="i">{{item}}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  ></el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                  >+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column label="参数名称" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-edit"
                    @click="editManyData(scope.row)"
                  >编辑</el-button>
                  <el-button
                    type="danger"
                    size="mini"
                    icon="el-icon-delete"
                    @click="deleteManyData(scope.row)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="静态属性" name="only">
            <el-button type="primary" size="mini" :disabled="isdisab" @click="showManyDate">添加属性</el-button>
            <el-table :data="onlyTableList" style="width: 100%" border stripe>
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag @close="removeTag(i,scope.row)" closable v-for=" (item,i) in scope.row.attr_vals" :key="i">{{item}}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  ></el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                  >+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column label="参数名称" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" size="mini" icon="el-icon-edit">编辑</el-button>
                  <el-button type="danger" size="mini" icon="el-icon-delete">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
        <el-dialog
          @close="addDialogClose"
          :title="newname"
          :visible.sync="showDialogVisible"
          width="50%"
        >
          <el-form
            :model="addParamsForm"
            :rules="addParamsrules"
            ref="addParamsRef"
            label-width="120px"
          >
            <el-form-item :label="newname" prop="attr_name">
              <el-input v-model="addParamsForm.attr_name"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="showDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addParamsSub">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 编辑分类的对话框 -->
        <el-dialog
          @close="editDialogClose"
          title="编辑分类"
          :visible.sync="editDialogVisible"
          width="50%"
        >
          <el-form
            :model="editParamsForm"
            :rules="editParamsrules"
            ref="editParamsRef"
            label-width="120px"
          >
            <el-form-item label="编辑分类" prop="attr_name">
              <el-input v-model="editParamsForm.attr_name"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editDataDialogVisible">确 定</el-button>
          </span>
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>

<script>
import { async } from "q";
export default {
  data() {
    return {
      paramsList: [],
      cascAllData: [],
      getPropsParams: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id"
      },
      activeName: "many",
      onlyTableList: [],
      manyTableList: [],
      showDialogVisible: false,
      editDialogVisible: false,

      addParamsForm: {
        attr_name: ""
      },
      editParamsForm: {
        attr_name: "",
        attrId: 0
      },
      addParamsrules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" }
        ]
      },
      editParamsrules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    // 获取数据
    async getCascList() {
      const res = await this.axios.get("categories");
      if (res.meta.status !== 200) return this.$mg.error(res.meta.msg);
      this.$mg.success(res.meta.msg);
      this.paramsList = res.data;
      console.log(this.paramsList);
    },
    // 点击属性
    async cascderHandleChange() {
      this.getParams();
    },
    //   获取数据 封装成函数
    async getParams() {
      if (this.cascAllData.length != 3) {
        this.cascAllData = [];
        this.manyTableList = [];
        this.onlyTableList = [];
        return;
      }
      const res = await this.axios.get(`categories/${this.cascId}/attributes`, {
        params: {
          sel: this.activeName
        }
      });
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        item.inputVisible = false;
        item.inputValue = "";
      });

      if (res.meta.status !== 200) return this.$mg.error(res.meta.msg);
      if (this.activeName == "only") {
        this.onlyTableList = res.data;
      } else {
        this.manyTableList = res.data;
      }
    },
    //   点击参数
    tabHandleClick() {
      this.getParams();
    },
    showManyDate() {
      this.showDialogVisible = true;
    },
    //   添加参数
    addParamsSub() {
      this.$refs.addParamsRef.validate(async falg => {
        if (!falg) return;
        const res = await this.axios.post(
          `categories/${this.cascId}/attributes`,
          {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.activeName
          }
        );
        if (!res.meta.status == 201) {
          return;
        }
        this.$mg.success(res.meta.msg);
        this.getParams();
        this.showDialogVisible = false;
      });
    },
    //  重置表单
    addDialogClose() {
      this.$refs.addParamsRef.resetFields();
    },
    // 重置表单
    editDialogClose() {
      this.$refs.editParamsRef.resetFields();
    },
    // 点击编辑按钮将数据渲染到input框中
    editManyData(data) {
      console.log(data);
      this.editDialogVisible = true;
      this.editParamsForm.attr_name = data.attr_name;
      this.editParamsForm.attrId = data.attr_id;
    },
    // 删除参数
    deleteManyData(data) {
      this.$cfm("此操作将永久删除该属性, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const res = await this.axios.delete(
            `categories/${this.cascId}/attributes/${data.attr_id}`
          );
          this.getParams();
        })
        .catch(() => {
          this.$mg.error(res.meta.msg);
        });
    },
    //    编辑参数
    editDataDialogVisible() {
      this.$refs.editParamsRef.validate(async falg => {
        if (!falg) return;
        const res = await this.axios.put(
          `categories/${this.cascId}/attributes/${this.editParamsForm.attrId}`,
          {
            attr_name: this.editParamsForm.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status !== 200) return this.$mg.error(res.meta.msg);
        this.editDialogVisible = false;
        this.getParams();
        this.$mg.success(res.meta.msg);
      });
    },
    // 当触发回车和失去焦点事件后触发 添加tag标签
  handleInputConfirm (row) {
            if(row.inputValue.trim().length === 0){
                row.inputVisible = false;
                row.inputValue = '';
                return
            }
            row.attr_vals.push(row.inputValue)
            this.editTag(row)
    },
  async editTag(row){
            const res = await this.axios.put(`categories/${this.cascId}/attributes/${row.attr_id}`,{
                attr_name:row.attr_name,
               attr_sel:this.activeName,
               attr_vals:row.attr_vals.join(',')
            })
           if(res.meta.status!==200) return
                this.$mg.success(res.meta.msg);
                row.inputVisible = false;
                row.inputValue = '';
            
    },
    // 点击添加tag标签的时候获得焦点
   showInput(row) {
      row.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 删除参数标签
     removeTag(i,row){
      row.attr_vals.splice(i,1)
        console.log(row.attr_vals);
        this.editTag(row)
    }
  },
  computed: {
    isdisab() {
      if (this.cascAllData.length != 3) {
        return true;
      }
      return false;
    },
    cascId() {
      if (this.cascAllData.length != 3) {
        return null;
      }
      return this.cascAllData[this.cascAllData.length - 1];
    },
    newname() {
      if (this.activeName == "many") {
        return "添加动态参数";
      }
      return "修改静态属性";
    }
  },
  created() {
    this.getCascList();
  }
};
</script>

<style lang='less' scoped>
.el-tag {
  margin: 7px;
}
.el-input {
  width: 150px;
}
</style>
